package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Praise;
import cn.wolfcode.trip.base.domain.Question;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.mapper.QuestionMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IQuestionService;
import cn.wolfcode.trip.base.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class QuestionServiceImpl implements IQuestionService {
    @Autowired
    private QuestionMapper questionMapper;

    @Override
    public void saveOrUpdate(Question entity) {
        User user = UserContext.getUserAttribute();
        if (entity.getId() == null) {
            entity.setUser(user);
            entity.setCreateTime(new Date());
            questionMapper.insert(entity);
        }else{
            questionMapper.updateByPrimaryKey(entity);
        }
    }

    @Override
    public PageInfo query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),qo.getOrderBy());
        List<Question> list = questionMapper.selectForList(qo);
        return new PageInfo(list);
    }

    @Override
    public Map<String,Object> selectByPrimaryKey(Long questionId) {
        Integer contents = questionMapper.queryCommentCount(questionId);
        Question question = questionMapper.selectByPrimaryKey(questionId);
        Map<String,Object> map = new HashMap<>();
        map.put("question",question);
        map.put("contents",contents);
        return map;
    }

    @Override
    public void updateBrowseNumber(Long questionId) {
        questionMapper.updateBrowseNumber(questionId);
    }

    @Override
    public Boolean queryIsLike(Praise obj) {
        String s = questionMapper.queryIsLike(obj);
        if(s==null){
            return false;
        }
        return true;
    }

    @Override
    public void saveDailyIsLike(Praise obj) {
        questionMapper.updatePraiseNumber(obj.getQuestionId());
        questionMapper.saveQuestionIsLike(obj);
    }

    @Override
    public void deleteDailyIsLike(Praise obj) {
        questionMapper.subPraiseNumber(obj.getQuestionId());
        questionMapper.deleteQuestionIsLike(obj);
    }
}
